from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from .models import City, Room, Host
from rest_framework.exceptions import PermissionDenied
from rest_framework import serializers, status


class CitySerializer(serializers.ModelSerializer):
    class Meta:
        model = City
        fields = '__all__'
        # 仅读字段
        read_only_fields = ['fcd', 'lcd','host_count']


class CityViewSet(ModelViewSet):
    queryset = City.objects.all()
    serializer_class = CitySerializer


class RoomSerializer(serializers.ModelSerializer):
    class Meta:
        model = Room
        fields = '__all__'
        # 仅读字段
        read_only_fields = ['id','fcd', 'lcd','host_count']


class RoomViewSet(ModelViewSet):
    queryset = Room.objects.all()
    serializer_class = RoomSerializer



class HostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Host
        fields = '__all__'
        # 仅读字段
        read_only_fields = ['id','fcd', 'lcd']


class HostViewSet(ModelViewSet):
    queryset = Host.objects.all()
    serializer_class =HostSerializer

    @action(detail=True, methods=['GET'])
    def ping(self, request, *args, **kwargs):
        mdl = self.get_object()
        # 探测主机是否 ping 可达逻辑
        result={
            "ip":mdl.ip,
            "ping":True
        }
        return Response(result, status=status.HTTP_200_OK)
